
import store from '@/store'
import Axios from 'axios'
import { Message } from 'element-ui'

const request = Axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})
request.interceptors.request.use(
  function(config) {
    // 1.请求添加token步骤
    //    引入store获取user模块的token
    //    判断是否有token
    //    有token将token添加至Authorization
    const Token = store.state.user.token
    if (Token) {
      config.headers.Authorization = 'Bearer ' + Token
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  })
request.interceptors.response.use(
  function(response) {
    if (response.data instanceof Blob) return response.data
    if (response.data.success) {
      Message.success(response.data.message)
      return response.data
    } else {
      Message.error(response.data.message)
      return Promise.reject(new Error(response.data.message))
    }
  },
  function(error) {
    if (error.response.status === 401) {
      store.commit('user/removeToken')
      store.commit('user/setUserInfo', {})
      store.commit('user/setToken', '')
    }
    return Promise.reject(error)
  })

export default request
